package com.blb.edufileservice.controller;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
public class UploadController {

    @Value("${file-server.ip}")
    private String fileServer;

    @Autowired
    private FastFileStorageClient client;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ResponseEntity<String> upload(MultipartFile file) throws IOException {
        //获得后缀名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        //上传
        StorePath storePath = client.uploadFile(file.getInputStream(), file.getSize(), extension, null);
        String url = "http://" + fileServer + "/" + storePath.getFullPath();
        log.info("url:{}" , url);
        return ResponseEntity.ok(url);
    }
}
